<!-- 业务范围 -->
<template>
  <div class="ywfw" v-loading="loading">
    <div class="top-head">
      <div class="form">
        <label style="margin-right: 10px">业务范围</label>
        <el-select
          v-model="ywbm"
          clearable
          filterable
          multiple
          collapse-tags
          @change="ywbmChange"
        >
          <el-option
            v-for="item in ywbmList"
            :key="item.dm"
            :label="item.mc"
            :value="item.dm"
          >
          </el-option>
        </el-select>
      </div>
      <el-button type="primary" @click="saveData" v-if="ywbm.length"
        >保存</el-button
      >
    </div>
    <div class="content" v-for="item in ywfwList" :key="item.dm">
      <div class="section">{{ item.mc }}</div>
      <div class="box">
        <el-descriptions :column="2" border>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-user"></i>
              案件类别
            </template>
            <new-tree-select
              style="width: 100%"
              node-key="dm"
              :defaultProps="ajlbProps"
              v-model="item.ajlbbmList"
              :data="item.ajlbList"
              multiple
              batchReverseElection
              checkStrictly
              showAllSelection
              collapse-tags
            ></new-tree-select>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </div>
  </div>
</template>
<script>
import sjzdService from '@/api/sjzd.js'
import wjfwService from '@/api/wjfw.js'
import laglService from '@/api/lagl.js'
/** 读取blob中的数据 */
const readBlobAsText = blob => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()

    reader.onload = () => {
      resolve(reader.result)
    }

    reader.onerror = event => {
      reject(event.target.error)
    }

    reader.readAsText(blob)
  })
}
export default {
  name: 'ywfw',
  props: {
    tdbh: String
  },
  data () {
    return {
      loading: false,
      ywbm: [],
      // 业务编码下拉列表
      ywbmList: [],
      // 案件类别下拉列表
      ajlbList: [],
      ajlbProps: {
        children: 'children',
        label: 'mc'
      },
      // 根据选择的业务范围展示数据
      ywfwList: []
    }
  },
  watch: {
    tdbh: {
      handler (val) {
        if (val) {
          this.queryTdyw(val)
        }
      },
      immediate: true
    }
  },
  mounted () {
    // 获取业务范围
    this.getYwfwList()
    this.getAjlbList()
  },
  methods: {
    /* 获取业务范围 */
    getYwfwList () {
      sjzdService.queryLayw({}).then(res => {
        this.ywbmList = res
      })
    },
    /** 业务编码改变 */
    ywbmChange (ywbm) {
      const arr = this.ywbmList.filter(item => ywbm.includes(item.dm))
      // 查找之前是否已选择案件类别
      arr.forEach(item => {
        const data = this.ywfwList.filter(_item => _item.dm === item.dm)
        if (data.length) {
          item.ajlbbmList = data[0].ajlbbmList
        }
      })
      // 案件类别默认只展示当前业务范围的类别
      this.ywfwList = arr.map(item => {
        return {
          ...item,
          ajlbList: this.ajlbList.filter(_item => _item.dm === item.dm)
        }
      })
    },

    /** 获取团队业务 */
    queryTdyw (tdbh) {
      this.loading = true
      laglService
        .queryTdyw({
          tdbh
        })
        .then(res => {
          // 循环下载当前数据
          this.downloadText(res)
        })
        .catch(err => {
          !err.isError &&
            this.$message({ type: 'warning', message: err.message })
        })
        .finally(() => {
          this.loading = false
        })
    },

    /** 循环下载当前数据 */
    downloadText (data) {
      Promise.all(
        data.map(item =>
          wjfwService.download({
            wjbh: item.pzccbh,
            wjmc: item.ywmc
          })
        )
      )
        .then(res => {
          // 读取当前blob的数据(当前返回的promise对象)
          const txtList = res.map(async item =>
            JSON.parse(await readBlobAsText(item))
          )
          // this.ajlbList.filter(item => item.dm === dm)||[]
          this.initData(txtList)
        })
        .catch(err => {
          !err.isError &&
            this.$message({ type: 'warning', message: err.message })
        })
    },

    /** 初始化数据 */
    initData (list) {
      Promise.all(list)
        .then(res => {
          this.ywbm = res.map(item => item.dm)
          // 案件类别默认只展示当前业务范围的类别
          this.ywfwList = res.map(item => {
            return {
              ...item,
              ajlbList: this.ajlbList.filter(_item => _item.dm === item.dm)
            }
          })
        })
        .catch(err => {
          console.error(err)
        })
    },

    /** 保存按钮 */
    saveData () {
      const { ywfwList } = this
      // 先将所有数据转文本格式
      const files = ywfwList.map(item => {
        return this.strToTxt(item)
      })
      this.loading = true
      // 循环调用已选择数据上传接口
      Promise.all(files.map(item => wjfwService.upload(item))).then(res => {
        const pzccbh = res.map(el => {
          return el.wjbh
        })
        this.saveTdyw(pzccbh)
      })
    },

    /** 循环调用保存接口 */
    saveTdyw (pzccbh) {
      const { tdbh, ywfwList } = this
      // 循环调用保存接口
      Promise.all(
        pzccbh.map((_item, i) => {
          const params = {
            pzccbh: _item,
            tdbh,
            ywbm: ywfwList[i].dm, // 当前数组的下标和选择的数据的下标所对应
            ywmc: ywfwList[i].mc //
          }
          return laglService.saveTdyw(params)
        })
      )
        .then(res => {
          this.$message({ type: 'success', message: '保存成功' })
        })
        .catch(err => {
          !err.isError &&
            this.$message({ type: 'warning', message: err.message })
        })
        .finally(() => {
          this.loading = false
        })
    },

    /* 获取案件类别下拉列表 */
    getAjlbList () {
      sjzdService
        .queryAjlb()
        .then(res => {
          this.ajlbList = this.$getTreeData(res, 'dm', 'fdm')
        })
        .catch(err => {
          !err.isError &&
            this.$message({ type: 'warning', message: err.message })
        })
    },

    /** 先将填写的数据转为text */
    strToTxt (data) {
      const str = JSON.stringify(data)
      const blob = new Blob([str])
      const file = new File([blob], data.mc + '.txt', { type: 'text/json' })
      const formData = new FormData()
      formData.append('file', file)
      return formData
    }
  }
}
</script>
<style lang="scss" scoped>
.ywfw {
  width: 100%;
  height: 100%;
  padding: 10px;
  .top-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 50px;
  }
  .content {
    margin-top: 15px;
    .section {
      display: flex;
      align-items: center;
      &::before {
        content: '';
        background-color: #4084f0;
        width: 5px;
        height: 20px;
        margin-right: 10px;
      }
    }
    .box {
      margin-top: 10px;
      /deep/ .el-descriptions .is-bordered .el-descriptions-item__cell {
        padding: 10px;
      }
    }
  }
}
/deep/ .el-select .el-select__tags {
  display: flex !important;
  align-items: center;
  flex-wrap: nowrap;
  > span {
    width: 100%;
    display: flex;
    align-items: center;
  }
}
</style>
